const https = require("https");
const http=require('http');
const { reject } = require("async");
class JQHttpContent {
    
	static async curl(url,params,is_json,method){
		let param_pairs=[];
		if(params){
			params.forEach((value,key)=>{
				param_pairs.push(`${key}=${value}`);
			});
		}
		if(param_pairs){
			if(url.indexOf('?')>-1)url = `${url}&${param_pairs.join('&')}`;
			else url = `${url}?${param_pairs.join('&')}`;
		}
		console.log('http:start' + url);
		
		let promise = new Promise((resolve, reject)=>{
		
			let http_module = https;
			if(url.toLowerCase().startsWith('http://'))http_module=http;
			let func = http_module.get;
			if(method =='POST')func = http_module.post;
			
			
			func(url,(req,res)=>{  
				let  content='';  
				
				req.on('data',(data)=>{  
						content+=data;  
				});  
				req.on('end',()=>{  
					let obj = null;
					if(is_json){
						try{
							obj = JSON.parse(content);
						}catch(e){
							console.log('http_content::' + e.message);
							reject({'code':global.Error.ERROR_HTTP,
								'message':global.Message.ERROR_HTTP});
						}
					}else{
						obj = content;
					}
				   console.log('get::'+content);
				   resolve(obj);
					  
				}); 
				req.on('error',(e)=>{
					console.log('http_content::' + e.message);
					//console.log('wsserror::'+ JSON.stringify(e));
					reject({'code':global.Error.ERROR_HTTP,
						'message':global.Message.ERROR_HTTP});
						
				});
					
			});
		});
		return promise;
	}
	
	static async get(url,params,is_json){
		return await JQHttpContent.curl(url,params,is_json,'GET');
	}
	static async post(url,params,is_json){
		return await JQHttpContent.curl(url,params,is_json,'POST');
	}
	
	
}
module.exports = JQHttpContent;
